/****************************************************************************
 * Copyright (C) 2012
 * by Dj_Skual
 *
 * This software is provided 'as-is', without any express or implied
 * warranty. In no event will the authors be held liable for any
 * damages arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any
 * purpose, including commercial applications, and to alter it and
 * redistribute it freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you
 * must not claim that you wrote the original software. If you use
 * this software in a product, an acknowledgment in the product
 * documentation would be appreciated but is not required.
 *
 * 2. Altered source versions must be plainly marked as such, and
 * must not be misrepresented as being the original software.
 *
 * 3. This notice may not be removed or altered from any source
 * distribution.
 *
 * TitleBrowser.cpp
 *
 * for SaveGame Manager GX 2012
 ***************************************************************************/
#include "../Themes/CTheme.h"
#include "../Controls/Application.h"
#include "../Prompts/PromptWindows.h"
#include "../System/sys.h"
#include "TitleBrowser.hpp"

#define LISTSIZE	10

TitleBrowser::TitleBrowser()
	:GuiFrame(0, 0)
{
	titleList = new TitleList();
	
	numEntries = titleList->GetCount();
	selectedItem = 0;
	pageIndex = 0;
	col2Setted = false;
	
	btnSoundClick = Resources::GetSound("button_click.wav");
	btnSoundOver = Resources::GetSound("button_over.wav");
	btnSoundClick->SetVolume(Settings.SFXVolume);
	btnSoundOver->SetVolume(Settings.SFXVolume);
	
	trigA = new SimpleGuiTrigger(-1, WiiControls.ClickButton | ClassicControls.ClickButton << 16, GCControls.ClickButton);
	trigB = new GuiTrigger();
	trigB->SetButtonOnlyTrigger(-1, WiiControls.BackButton | ClassicControls.BackButton << 16, GCControls.BackButton);
	
	WindowImgData = Resources::GetImageData("dialogue_box.png");
	BrowserImgData = Resources::GetImageData("browser.png");
	ButtonBoxImgData = Resources::GetImageData("browser_select_button_box.png");
	ListSelectionImgData = Resources::GetImageData("browser_bg_selection.png");

	width = WindowImgData->GetWidth();
	height = WindowImgData->GetHeight();
	
	WindowImg = new GuiImage(WindowImgData);
	WindowImg->SetScaleY(1.35);
	WindowImg->SetPosition(0, -20);
	
	BrowserImg = new GuiImage(BrowserImgData);
	BrowserImg->SetAlignment(ALIGN_CENTER | ALIGN_TOP);
	BrowserImg->SetScaleX(0.645);
	BrowserImg->SetScaleY(1.05);
	BrowserImg->SetPosition(-23, 8);
	
	ButtonBoxImg = new GuiImage(ButtonBoxImgData);
	ButtonBoxImg->SetAlignment(ALIGN_RIGHT | ALIGN_TOP);
	ButtonBoxImg->SetPosition(-25, -42);
	
	TitleText = new GuiText(tr( "Title Launcher" ), 22, thColor("r=0 g=0 b=0 a=255 - prompt windows text color"));
	TitleText->SetAlignment(ALIGN_CENTER | ALIGN_TOP);
	TitleText->SetPosition(-20, -47);
	TitleText->SetMaxWidth(255, SCROLL_HORIZONTAL);
	
	CloseBtn = new PictureButton("button_close.png", "button_close_over.png", btnSoundClick, btnSoundOver);
	CloseBtn->SetAlignment(ALIGN_RIGHT | ALIGN_TOP);
	CloseBtn->SetPosition(-28, -40);
	CloseBtn->SetTrigger(trigA);
	CloseBtn->SetTrigger(trigB);
	CloseBtn->Clicked.connect(this, &TitleBrowser::OnCloseBtnClick);
	
	Append(WindowImg);
	Append(BrowserImg);
	Append(ButtonBoxImg);
	Append(CloseBtn);
	Append(TitleText);
	
	ScrollBar = new Scrollbar(288, Scrollbar::CUSTOMMODE);
	ScrollBar->SetAlignment(ALIGN_RIGHT | ALIGN_TOP);
	ScrollBar->SetPosition(-30, 0);
	ScrollBar->SetScrollSpeed(Settings.ScrollSpeed);
	ScrollBar->listChanged.connect(this, &TitleBrowser::OnListChange);
	ScrollBar->SetButtonScroll(WiiControls.OneButtonScroll | ClassicControls.OneButtonScroll << 16, GCControls.OneButtonScroll);
	
	for(int i = 0; i < LISTSIZE; ++i)
		AddButton();
	
	ScrollBar->SetEntrieCount(numEntries);
	ScrollBar->SetPageSize(LISTSIZE);
	ScrollBar->SetRowSize(0);
	ScrollBar->SetSelected(0, 0);
	Append(ScrollBar);
	
	SetAlignment(ALIGN_CENTER | ALIGN_MIDDLE);
	SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50);
	
	Application::Instance()->Append(this);
	Application::Instance()->SetUpdateOnly(this);
}

TitleBrowser::~TitleBrowser()
{
	RemoveAll();

	delete WindowImg;
	delete BrowserImg;
	delete ButtonBoxImg;
	
	Resources::Remove(WindowImgData);
	Resources::Remove(BrowserImgData);
	Resources::Remove(ButtonBoxImgData);
	Resources::Remove(ListSelectionImgData);

	delete TitleText;

	delete ScrollBar;

	delete CloseBtn;
	
	delete trigA;
	delete trigB;
	
	Resources::Remove(btnSoundClick);
	Resources::Remove(btnSoundOver);
	
	while(ListBtn.size() > 0)
		RemoveButton(0);
	
	delete titleList;
}

void TitleBrowser::SetCol2()
{
	if(col2Setted)
		return;
	
	col2 = 0;
	for (int i = 0; i < titleList->GetCount()-1; i++)
	{
		GuiText * text = new GuiText(titleList->GetID(i).c_str(), 20 , (GXColor){0, 0, 0, 255});
		if (col2 < text->GetTextWidth())
			col2 = text->GetTextWidth();
		delete text;
	}
	
	col2 += 5;
	
	col2Setted = true;
}

void TitleBrowser::AddButton()
{
	SetCol2();
	
	int size = ListBtn.size();
	
	ListBtnID.resize(size+1);
	ListBtnID[size] = new GuiText((char*) NULL, 20, thColor("r=0 g=0 b=0 a=255 - prompt languageSelect list text color"));
	ListBtnID[size]->SetAlignment(ALIGN_LEFT | ALIGN_MIDDLE);
	ListBtnID[size]->SetPosition(365-col2, 0);
	
	ListBtnName.resize(size+1);
	ListBtnName[size] = new GuiText((char*) NULL, 20, thColor("r=0 g=0 b=0 a=255 - prompt languageSelect list text color"));
	ListBtnName[size]->SetAlignment(ALIGN_LEFT | ALIGN_MIDDLE);
	ListBtnName[size]->SetPosition(5, 0);
	ListBtnName[size]->SetMaxWidth(365-col2-10, DOTTED);
	
	ListBtnNameOver.resize(size+1);
	ListBtnNameOver[size] = new GuiText((char*) NULL, 20, thColor("r=0 g=0 b=0 a=255 - prompt languageSelect list text color"));
	ListBtnNameOver[size]->SetAlignment(ALIGN_LEFT |ALIGN_MIDDLE);
	ListBtnNameOver[size]->SetPosition(5, 0);
	ListBtnNameOver[size]->SetMaxWidth(365-col2-25, SCROLL_HORIZONTAL);
	
	ListSelectionImg.resize(size+1);
	ListSelectionImg[size] = new GuiImage(ListSelectionImgData);
	ListSelectionImg[size]->SetScaleX(0.95);
	ListSelectionImg[size]->SetPosition(-8, 0);
	
	ListBtn.resize(size+1);
	ListBtn[size] = new GuiButton(365, 28);
	ListBtn[size]->SetLabel(ListBtnName[size], 0);
	ListBtn[size]->SetLabel(ListBtnID[size], 1);
	ListBtn[size]->SetLabelOver(ListBtnNameOver[size], 0);
	ListBtn[size]->SetImageOver(ListSelectionImg[size]);
	ListBtn[size]->SetAlignment(ALIGN_CENTER | ALIGN_TOP);
	ListBtn[size]->SetPosition(-25, 28*size+4);
	ListBtn[size]->SetTrigger(trigA);
	ListBtn[size]->SetSoundClick(btnSoundClick);
	ListBtn[size]->SetRumble(Settings.BrowserRumble);
	ListBtn[size]->Clicked.connect(this, &TitleBrowser::OnListClick);
	ListBtn[size]->StateChanged.connect(this, &TitleBrowser::OnButtonStateChange);
	ListBtn[size]->SetState(STATE_DISABLED);
	
	Append(ListBtn[size]);
}

void TitleBrowser::RemoveButton(int i)
{
	if(i < 0 || i >= (int) ListBtn.size())
		return;

	if(ListBtnID[i])
		delete ListBtnID[i];
	if(ListBtnName[i])
		delete ListBtnName[i];
	if(ListBtnNameOver[i])
		delete ListBtnNameOver[i];
	if(ListSelectionImg[i])
		delete ListSelectionImg[i];
	if(ListBtn[i])
		delete ListBtn[i];

	ListBtnID.erase(ListBtnID.begin()+i);
	ListBtnName.erase(ListBtnName.begin()+i);
	ListBtnNameOver.erase(ListBtnNameOver.begin()+i);
	ListSelectionImg.erase(ListSelectionImg.begin()+i);
	ListBtn.erase(ListBtn.begin()+i);
}

void TitleBrowser::OnButtonStateChange(GuiElement *sender, int state, int stateChan UNUSED)
{
	for(int i = 0; i < LISTSIZE && i < titleList->GetCount(); i++)
	{
		if(sender == ListBtn[i])
		{
			if(state == STATE_SELECTED)
			{
				selectedItem = i;
				break;
			}
		}
	}
	
	if(ListBtn[selectedItem]->GetState() == STATE_DEFAULT)
		ListBtn[selectedItem]->SetState(STATE_SELECTED);
	
	ScrollBar->SetSelectedItem(selectedItem);
}

void TitleBrowser::OnListChange(int selItem, int selIndex)
{
	selectedItem = selItem;
	pageIndex = selIndex;
	
	for(int i = 0; i < LISTSIZE; i++)
	{
		if(pageIndex+i < numEntries)
		{
			if(ListBtn[i]->GetState() == STATE_DISABLED)
			{
				ListBtn[i]->SetVisible(true);
				ListBtn[i]->SetState(STATE_DEFAULT);
			}
			
			ListBtnID[i]->SetText(titleList->GetID(pageIndex+i));
			ListBtnName[i]->SetText(titleList->GetName(pageIndex+i));
			ListBtnNameOver[i]->SetText(titleList->GetName(pageIndex+i));
			
		}
		else
		{
			ListBtn[i]->SetVisible(false);
			ListBtn[i]->SetState(STATE_DISABLED);
		}
	}

	for(int i = 0; i < LISTSIZE; i++)
	{
		if(ListBtn[i]->GetState() == STATE_SELECTED && i != selectedItem)
			ListBtn[i]->SetState(STATE_DEFAULT);
	}
	
	ScrollBar->SetSelected(selectedItem, pageIndex);
}

void TitleBrowser::OnListClick(GuiButton *sender, int pointer UNUSED, const POINT &p UNUSED)
{
	Application::Instance()->ResetPads();
	
	for(int i = 0; i < (int)ListBtn.size(); ++i)
	{
		if(sender != ListBtn[i])
			continue;
		
		if(!Settings.vWii && ((pageIndex+i) == (numEntries-1)))
		{
			if(WindowPrompt(tr("Load:"), tr("Wii Settings"), tr("OK"), tr("Cancel")))
			{
				//!Launch Wii Settings
				ExitApp();
				WII_Initialize();
				WII_ReturnToSettings();
			}
		}
		else if(WindowPrompt(tr("Load:"), wstr2str(titleList->GetName(pageIndex+i)).c_str(), tr("OK"), tr("Cancel")))
		{
			//!Launch Title
			ExitApp();
			WII_Initialize();
			WII_LaunchTitle(titleList->GetTid(pageIndex+i));
		}
		
		break;
	}
}

void TitleBrowser::OnCloseBtnClick(GuiButton *sender UNUSED, int pointer UNUSED, const POINT &p UNUSED)
{
	Application::Instance()->ResetPads();
	
	SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50);
	
	Close();
}
